# coding=utf-8

#python
import os
import random
import logging
import webapp2

#appengine
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template

#lib
from const import *

#handlers
class RedirHandler(webapp.RequestHandler):
	def get(self):
		
		#Collect GEO Headers
		header_country=self.request.headers.get('X-AppEngine-Country', '')
		header_region=self.request.headers.get('X-AppEngine-Region', '')
		header_city=self.request.headers.get('X-AppEngine-City', '')
		header_citylatlong=self.request.headers.get('X-AppEngine-CityLatLong', '')
		
		#build params
		URL_PARAM_COUNTRY = {'form_param':"country_param",'form_param_transform':"country_param_transform",'redir_param':"country",'param_value':header_country}
		URL_PARAM_REGION = {'form_param':"region_param",'form_param_transform':"region_param_transform",'redir_param':"region",'param_value':header_region}
		URL_PARAM_CITY = {'form_param':"city_param",'form_param_transform':"city_param_transform",'redir_param':"city",'param_value':header_city}
		URL_PARAM_CITYLATLONG = {'form_param':"latlong_param",'form_param_transform':"latlong_param_transform",'redir_param':"latlong",'param_value':header_citylatlong}
		REDIR_PARAMS = [
			URL_PARAM_COUNTRY,
			URL_PARAM_REGION,
			URL_PARAM_CITY,
			URL_PARAM_CITYLATLONG
			]
		#sys params
		SYS_PARAMS = []
		SYS_PARAMS += [x['form_param'] for x in REDIR_PARAMS]
		SYS_PARAMS += [x['form_param_transform'] for x in REDIR_PARAMS]
		SYS_PARAMS += ['url']
			
		#record action
		logging.info("REDIR_PARAMS:%s", str(REDIR_PARAMS))

		#url
		final_url = self.request.get('url', None)
		if not final_url is None :
			final_url = str(final_url)
			
			#extract params
			params_pairs = []
			for param in REDIR_PARAMS:
				param_value = param['param_value']
				if len(param_value)>0:
					redir_param = self.request.get(param['form_param'],'')
					transform_param = self.request.get(param['form_param_transform'],'')
				
					if transform_param=='upper': param_value = param_value.upper()
					if transform_param=='lower': param_value = param_value.lower()
					if len(redir_param)>0:
						params_pairs.append("%s=%s" % (redir_param, param_value))
			
			#build query	
			query = "&".join(params_pairs)
			#add query to final url
			if final_url.find("?")==-1: 
				final_url += '?' + query
			else:
				final_url += '&' + query
			
			#append extra params not system params
			extra_params = []
			for field in self.request.arguments():
				if field not in SYS_PARAMS:
					extra_params.append("%s=%s" % (field, self.request.get(field)))
			if len(extra_params)>0:
				if final_url.find("?")==-1: 
					final_url += '?' + "&".join(extra_params)
				else:
					final_url += '&' + "&".join(extra_params)				
			
			#record action
			logging.info("extra_params:%s", str(extra_params))
			
			#check protocol
			if final_url[:4].lower()!='http':
				final_url = '//' + final_url

			#record action
			logging.info("final_url:%s", str(final_url))
			
			#redirect to the final destination
			self.redirect(str(final_url))
		else:
			#redirect to creation form
			self.redirect('/create')


app = webapp2.WSGIApplication(
									 [('.+', RedirHandler)],
									 debug=True)

